var express = require('express');
var router = express.Router();
var Mock = require("mockjs");//随机生成一些假数据
const s = new Intl.DateTimeFormat('zh-cn');//优化时间格式
// const crypto = require("crypto");//crypto模块功能是加密并生成各种散列
// const { stringify } = require("qs");//
const { Uid0, Movie, Vuer, Goodlist, Cartinfo, Addressinfo, Cityinfo } = require('../utils/schema.js');
const Random = Mock.Random;

const { keys, aesEncrypt, aesDecrypt } = require("../utils/index");
let getusername = "";

/***********************/
router.get("/demo", (req, res) => {
    res.json({
        code: 200,
        msg: "demo is success",
        query: req.query
    })
})

// mock假数据接口api
router.get("/mock/data", (req, res) => {
    let articles = [];
    for (let i = 0; i < 100; i++) {
        let newArticleObject = {
            uid: Random.id(),
            title: Random.csentence(5, 30),//句子段落
            city: Random.city(),
            thumbnail_pic_s: Random.image('200x200', '#02adea', 'wuhan1910'),
            author_name: Random.cname(),//中文名字
            date: Random.date('yyyy-MM-dd') + " " + Random.time()
        }
        articles.push(newArticleObject);
    };
    res.json({
        result: articles,
        code: 200,
        msg: "获取mock假数据成功!"
    })
})

router.get("/movie", (req, res) => {
    const { limit } = req.query;
    Movie.find({}, {}).limit(parseInt(limit)).sort({ _id: -1 }).then(data => {
        res.json({
            code: 200,
            msg: "获取电影数据列表",
            data
        })
    })
});

/***********************/
// 商品列表
router.get("/goodlist", (req, res) => {
    let itemType = req.query.itemType; // 前端已做处理
    if (!!itemType) {
        Goodlist.find({
            itemType
        }).then(result => {
            res.json({
                code: 200,
                msg: "获取商品列表成功!",
                result
            })
        }).catch(() => {
          res.json({
            code: 201,
            msg: "获取商品列表失败",
            result: null
          })
        })
    } else {
        Goodlist.find({}).then(result => {
            res.json({
                code: 200,
                msg: "获取商品列表成功!",
                result
            })
        }).catch(() => {
          res.json({
            code: 201,
            msg: "获取商品列表失败",
            result: null
          })
        })
    }

})

// search
// router.get("/good-search", (req, res) => {
//   // const {val} = req.query
//   // console.log(val)
//   // // console.log(req.query)
//   // Goodlist.$where('this.goods_id === 61543228').then(result => {
//   //   // console.log(result)
//   //   // 没用到,是通过vuex数据filter过滤得到的
//   // })
//   // Goodlist.find({ $where: this.goods_info.title.includes(val) }).then(result => {
//   //   console.log(result)
//   // })
//   // Goodlist.find({
//   //     title: new RegExp(val)
//   // }).then(result => {
//   //   console.log(result)
//   //     // res.json({
//   //     //     code: 200,
//   //     //     msg: "获取商品列表成功!",
//   //     //     result
//   //     // })
//   // }).catch(() => {
//   //   res.json({
//   //     code: 201,
//   //     msg: "获取商品列表失败",
//   //     result: null
//   //   })
//   // })
// })


router.post("/login", (req, res) => {
    var body = req.body;
    // console.log(body);
    Vuer.findOne({
        $or: [
            {
                username: body.username
            }, {
                mobile: body.mobile
            }
        ]
    }).then(result => {
        if (result) {
            // console.log("发生的纠纷");
            // console.log(result);
            if (result.password == body.password) {
                // req.session.uid = result.uid;
                // req.session.mobile = result.mobile;
                // 后端加密生成发送给前端,前端保存在sessionStorage里面
                const token = aesEncrypt(result.username, keys);
                req.session.token = token;//保存在后端的令牌
                // req.session.cookie.token = token;//保存在后端的令牌
                // console.log(req.session)
                // console.log('登录存储', req.session.token)
                res.json({
                    code: 200,
                    msg: "登录成功",
                    token
                });
            } else {
                res.json({
                    code: 201,
                    msg: "用户名或者密码错误",
                    token: null,
                });
            }
        } else {
            res.json({
                code: 0,
                msg: "用户名或者密码错误",
                token: null
            });
        }
    });
})


router.post("/register", (req, res) => {
    // 判断都在后端执行,前端只要保证传的数据合乎规范(比如判断用户名是否存在)
    let body = req.body;
    // console.log(req.body);
    // console.log(body);
    Vuer.findOne({
        username: body.username
    }).then(result => {
        if (result) {
            res.json({
                code: 0,
                msg: "注册失败",
                data: null
            });
        } else {
            Uid0.updateOne({//先存(刚开始是id:0;直接取是从0开始的,等更新后再取)
                username: "uniers"
            }, {
                $inc: {
                    id: 1
                }
            }).then(data => {
                // console.log(data);
                Uid0.findOne({//再取
                    username: "vuers"
                }).then(last => {
                    // console.log(last);

                    body.time = s.format(new Date());
                    body.vid = last.id;
                    Vuer.insertMany(body).then(data => {
                        res.json({
                            code: 200,
                            msg: "注册成功",
                            data: { username: body.username }
                        });
                    })
                })
            })
        }
    })
});



// 获取登录信息
router.post("/userinfo", (req, res) => {
    let { token } = req.body;
    getusername = aesDecrypt(token, keys);
    Vuer.findOne({
        username: getusername
    }).then(result => {
        res.json({
            code: 200,
            msg: "获取个人信息成功",
            result
        })
    }).catch(() => {
      res.json({
        code: 201,
        msg: "获取个人信息失败",
        result
    })
    })
})

// 上传头像-使用插件↓
const multer = require("multer");
// 存到磁盘
const storage = multer.diskStorage({
  // 存储地
  destination: function (req, file, cb) {
      // 失败回调null,和成功回调
      cb(null, './public/avatar') //执行的是app.js,所以是./
  },
  // 命名
  filename: function (req, file, cb) {
    // fieldname 由表单指定	originalname	用户计算机上的文件的名称
      // username = aesDecrypt(req.session.token, keys)
      cb(null, "user" + '-' + Date.now() + '.' + file.originalname.split('.')[1] )
  }
})
// 创建上传对象(any: 任何的数据类型,字段) -upload作为router的第二个参数
const upload = multer({ storage: storage }).any()
router.post("/upload-avatar", upload, (req, res) => {
    // 获取路径(处理: replace(/\\/g, "/") )和username
    const avatarpath = req.files[0].path.replace(/\\/g, "/");

    // authorization: 'e41e50fb3042033d5773f487abc3106d' // headers带来的
    // username = aesDecrypt(req.session.token, keys); // 登录时存在req.session中一刷就没了
    const user = aesDecrypt(req.headers.authorization, keys)

    Vuer.updateOne({ username: user }, { $set: { avatar: avatarpath } }).then(result => {
      res.json({
          code: 200,
          msg: "头像上传成功!",
          avatar: avatarpath
      })
    })
})

// 获取头像
router.post("/getavatar", (req, res) => {
    getusername = aesDecrypt(req.body.token, keys);
    Vuer.findOne({ username: getusername }).then(result => {
        if (!!result.avatar) {
            // console.log(result);
            res.json({
                code: 200,
                msg: "头像获取成功",
                avatar: result.avatar,
            })
        } else {
            res.json({
                code: 201,
                msg: "头像获取失败",
                avatar: null
            })
        }
    })
})


router.get("/details", (req, res) => {
    let tradeItemId = req.query.tradeItemId;
    Goodlist.findOne({
      goods_id: tradeItemId
    }).then(result => {
      // console.log(result)
        if (result) {
            res.json({
                code: 200,
                msg: "获取商品详情成功!",
                result
            })
        }
    }).catch(() => {
      res.json({
          code: 201,
          msg: "获取商品详情失败",
          result: null
      })
    })
})


// 加入购物车
router.post("/addcart", (req, res) => {
  // Cartinfo
  const info = req.body.info
  const token = req.body.token
  // const user = aesDecrypt(token, keys)
  // 不用解码 每个人的token是不同且一直不变化的
  const user = token
  
  // 得到tree的参数
  Goodlist.findOne({goods_id: info.goodsId}).then(good => {
    function search (sType, sVal) {
      const arr_k_s = good.sku.tree.filter(tree_k_s => {
        return tree_k_s.k_s === sType
      })
      const arr_v = arr_k_s[0].v.filter(tree_v => {
        return tree_v.id === sVal
      })
      return arr_v[0].name
    }
    const obj = {...info, selectedId: info.selectedSkuComb.id, s1:search('s1', info.selectedSkuComb.s1), s2:search('s2', info.selectedSkuComb.s2), user, goods_info: good.goods_info }
    // console.log(obj)
    // 添加或更新
    Cartinfo.findOne({user, goodsId: obj.goodsId, selectedId: obj.selectedId}).then(result => {
      if (result) {
        Cartinfo.updateOne({user: result.user, goodsId: result.goodsId, selectedId: result.selectedId},{
          $set: {
            selectedNum: result.selectedNum*1+obj.selectedNum*1
          }
        }).then(updateres => {
          // {n: 1, nModified: 1, ok: 1 }
          if (updateres.nModified === 1) {
            res.json({
              code: 200,
              msg: '加购成功',
              result: obj.goodsId + '&' + obj.selectedId + '&' + obj.selectedNum
            })
          } else {
            res.json({
              code: 201,
              msg: '加购失败',
              result: null
            })
          }
        })
      } else {
        Cartinfo.insertMany({...obj}).then(addres => {
          if (addres.length > 0) {
            res.json({
              code: 200,
              msg: '加购成功',
              result: obj.goodsId + '&' + obj.selectedId + '&' + obj.selectedNum
            })
          } else {
            res.json({
              code: 201,
              msg: '加购失败',
              result: null
            })
          }
        })
      }
    })
  })
  
})

// 获取购物车数据
router.post('/cart', (req, res) => {
  Cartinfo.find({...req.body}).then(result=>{
    res.json({
      code: 200,
      msg: '购物车数据',
      result
    })
  })
})

// 购物车加减
router.post('/addsub', (req, res) => {
  const item = req.body.item
  Cartinfo.findOne({user: item.user, goodsId: item.goodsId, selectedId: item.selectedId}).then(result => {
    // console.log(result)
    if (result) {
      Cartinfo.updateOne({user: result.user, goodsId: result.goodsId, selectedId: result.selectedId},{
        $set: {
          selectedNum: item.selectedNum
        }
      }).then(updateres => {
        // {n: 1, nModified: 1, ok: 1 }
        if (updateres.nModified === 1) {
          res.json({
            code: 200,
            msg: 'add&sub',
            result: null
          })
        }
      })
    }
  })
})

// 购物车删除
router.post('/cart-delete', (req, res) => {
  const item = req.body.item
  Cartinfo.findOne({user: item.user, goodsId: item.goodsId, selectedId: item.selectedId}).then(result => {
    // console.log(result)
    if (result) {
      Cartinfo.deleteOne({user: result.user, goodsId: result.goodsId, selectedId: result.selectedId}).then(delete_res => {
        // {n: 1, nModified: 1, ok: 1 }
        if (delete_res.deletedCount === 1) {
          res.json({
            code: 200,
            msg: '已删除单条数据',
            result: null
          })
        }
      })
    }
  })
})

// 购物车删除全部
router.post('/cart-deleteall', (req, res) => {
  Cartinfo.remove({...req.body}).then(del_res => {
    // { n: 6, ok: 1, deletedCount: 6 }
    if (del_res.deletedCount) {
      res.json({
        code: 200,
        msg: '已删除全部数据',
        result: del_res
      })
    }
  })
})


// 加地址
router.post('/add-area', (req, res) => {
  Addressinfo.insertMany(req.body.content).then(result => {
    res.json({
      code: 200,
      msg: '添加地址成功',
      result
    })
  })
})

// 取地址列表
router.post('/getarea', (req, res) => {
  Addressinfo.find({user: req.body.token}).then(result => {
    res.json({
      code: 200,
      msg: '添加地址成功',
      result
    })
  })
})

// 改默认
router.post('/modify-area', (req, res) => {
  Addressinfo.updateMany({user: req.body.user}, {
    $set:{
      isDefault: false
    }
  }).then(all => {
    // { n: 2, nModified: 1, ok: 1 }

    Addressinfo.updateOne(req.body,{
      $set:{
        isDefault: true
      }
    }).then(result => {
      if (result.n) {
        // 获取新值
        Addressinfo.find({user: req.body.user}).then(result2 => {
          res.json({
            code: 200,
            msg: '修改默认地址成功',
            result: result2
          })
        })
      }
    })
  })
})

// 由id更改modify-item
router.post('/modify-item', (req, res) => {
  let obj =req.body
  delete obj.isDefault //不更改原来的默认属性, 此方法返回布尔值
  console.log(obj)
  Addressinfo.updateOne({user: obj.user, id: obj.id}, {
    $set:{
      ...obj
    }
  }).then(all => {
    if (all.nModified) {
      res.json({
        code: 200,
        msg: '修改地址成功',
        result: all
      })
    }
  })
})

// 删地址
router.post('/delete-area', (req, res) => {
  Addressinfo.deleteOne({...req.body}).then(one => {
    if (one.deletedCount) {
      Addressinfo.find({user: req.body.user}).then(result => {
        res.json({
          code: 200,
          msg: '删除成功',
          result
        })
      })
    }
  })
})

router.get('/cities', (req, res) => {
  Cityinfo.find({}).then(result => {
    if (result.length) {
      res.json({
        code: 200,
        msg: '获取地址成功',
        result
      })
    }
  })
})
// 导出路由
module.exports = router;
